/*
 * Name: Joon Ho Cho
 * Date: 10/24/2008
 * Course: 15-437
 */
package scheduler.model;


import org.mybeans.dao.DAOException;
import org.mybeans.factory.BeanTable;
import org.mybeans.factory.MatchArg;
import org.mybeans.factory.RollbackException;
import org.mybeans.dao.GenericDAO;
import org.mybeans.factory.Transaction;

import scheduler.databean.SavedSchedule;

public class SavedScheduleDaoBeanFactoryImpl
    extends GenericDAO<SavedSchedule> 
    implements SavedScheduleDao { 
	
    public SavedScheduleDaoBeanFactoryImpl(String dbDriver, String dbUrl) {
        this(BeanTable.getSQLInstance(SavedSchedule.class, "savedSchedule", dbDriver, dbUrl));
    }
    
    private SavedScheduleDaoBeanFactoryImpl(BeanTable<SavedSchedule> table) {
        super(table, "id");
        getTable().setIdleConnectionCleanup(true);
        setUseAutoIncrementOnCreate(true);
    }
    
    public SavedSchedule[] getSavedSchedules(String userName) throws DAOException {
        try {
            return getFactory().match(MatchArg.equals("userName", userName));
            
        } catch (RollbackException e) {
            throw new DAOException(e);
        }
    }
    
    public SavedSchedule getCurrentSchedule(String userName) throws DAOException {
        try {
            return getFactory().match(MatchArg.equals("userName", userName), MatchArg.equals("isCurrentSchedule", true))[0];
        } catch (RollbackException e) {
            throw new DAOException(e);
        }
    }
    
    public SavedSchedule create() throws DAOException {
        try {
            return getFactory().create();
        } catch (RollbackException e) {
            throw new DAOException(e);
        }
    }
    
    public SavedSchedule create(String userName, boolean isCurrentSchedule, int year, String semester, int[] scheduledIds, String[] courseNames)
        throws DAOException {
        try {
            Transaction.begin();
            SavedSchedule newSchedule = create();
            newSchedule.setUserName(userName);
            newSchedule.setIsCurrentSchedule(isCurrentSchedule);
            newSchedule.setYear(year);
            newSchedule.setSemester(semester);
            newSchedule.setScheduleIds(scheduledIds);
            newSchedule.setCourseNames(courseNames);
            Transaction.commit();
            return newSchedule;
        } catch (RollbackException e) {
            throw new DAOException(e);
        }
    }
    
    public SavedSchedule lookup(int id) throws DAOException {
        try {
            return getFactory().lookup(id);
        } catch (RollbackException e) {
            throw new DAOException(e);
        }
    }
    
    public void delete(int id) throws DAOException {
        try {
            getFactory().delete(id);
        } catch (RollbackException e) {
            throw new DAOException(e);
        }
    }
}
